import React, { Component } from 'react';
import Header from '../../components/Header'
import {getBannerList,getNavList, getProList} from '../../api/home'
import {Swiper,Image, Grid, AutoCenter, InfiniteScroll } from 'antd-mobile'
import './index.scss'

import ProList from '../../components/ProList';

class index extends Component {

  state = {
    bannerList: [],
    navList: getNavList(),
    proList: [],
    hasMore: true, // 是用来标记是否还有更多的数据
    count: 1, // 当前页码
  }

  componentDidMount(){
    getBannerList().then(res => {
      console.log(res);
      this.setState({
        bannerList: res.data
      })
    })

    // getProList({count: this.state.count}).then(res => {
    //   console.log(res.data);
    //   this.setState({
    //     proList: res.data,
    //     count: this.state.count + 1
    //   })
    // })

  }

  render() {

    // 用户上拉加载的时候回调的函数
    const loadMore = async ()=>{
      // 默认获取的是第一页的数据
      // 当用户上拉之后我们可以获取第二页的数据

      await getProList({count: this.state.count}).then(res => {

        if(res.data.length > 0){
          // 有数据
          this.setState({
            proList: [...this.state.proList, ...res.data],
            count: this.state.count + 1
          })
        }else {
          // 没有更多数据
          this.setState({
            hasMore: false
          })
        }


      })
    }

    return (
      <div className='box'>
          <Header title='首页' />
          <div className='content'>

            {/* 轮播图布局 */}
            {this.state.bannerList && (<Swiper className='my-swiper' autoplay loop>
              {this.state.bannerList.map(item => {
                return (<Swiper.Item key={item.bannerid}>
                  <Image src={item.img} />
                </Swiper.Item>)
              })}
            </Swiper>)}

            {/* 栅格布局 */}
            <Grid columns={5} gap={18}>
              {this.state.navList && this.state.navList.map(item => {
                return (<Grid.Item key={item.navid}>
                  <AutoCenter >
                    <Image width={44} height={44} src={item.imgurl} />
                    <div style={{textAlign: 'center'}}> {item.title} </div>
                  </AutoCenter>
                  </Grid.Item>)
              })}
            </Grid>

            {/* 商品展示 */}
            <ProList proList={this.state.proList} />


            {/* 上拉加载更多 */}
            {/* hasMore是否还有更多数据，loadMore上拉之后的回调函数 */}
            <InfiniteScroll hasMore={this.state.hasMore} loadMore={loadMore} />

          </div>
        </div>
    );
  }
}

export default index;
